package com.sky.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.net.URL;
import java.util.Date;

@Data
@AllArgsConstructor
@Slf4j
public class AliOssUtil {

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

    /**
     * 创建OSS客户端实例
     */
    private OSS createOssClient() {
        return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 文件上传到私有Bucket
     *
     * @param bytes     文件字节数组
     * @param objectName 对象名称
     * @param expireTime 签名URL有效期（毫秒）
     * @return 带有签名的访问URL
     */
    public String uploadToPrivateBucket(byte[] bytes, String objectName, long expireTime) {
        OSS ossClient = createOssClient();

        try {
            // 上传文件
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));

            // 生成带签名的URL
            return generatePresignedUrl(ossClient, objectName, expireTime);

        } catch (OSSException oe) {
            log.error("OSS异常: Error Message: {}, Error Code: {}, Request ID: {}, Host ID: {}",
                    oe.getErrorMessage(), oe.getErrorCode(), oe.getRequestId(), oe.getHostId());
            throw new RuntimeException("OSS操作失败", oe);
        } catch (ClientException ce) {
            log.error("客户端异常: {}", ce.getMessage());
            throw new RuntimeException("OSS客户端错误", ce);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 生成预签名URL
     *
     * @param objectName 对象名称
     * @param expireTime 过期时间（毫秒）
     * @return 带签名的URL
     */
    public String generatePresignedUrl(String objectName, long expireTime) {
        OSS ossClient = createOssClient();
        try {
            return generatePresignedUrl(ossClient, objectName, expireTime);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 内部生成预签名URL方法
     */
    private String generatePresignedUrl(OSS ossClient, String objectName, long expireTime) {
        // 设置URL过期时间
        Date expiration = new Date(System.currentTimeMillis() + expireTime);

        // 生成预签名URL
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName);
        request.setExpiration(expiration);

        // 可以指定HTTP方法（默认GET）
        // request.setMethod(HttpMethod.GET);

        URL signedUrl = ossClient.generatePresignedUrl(request);
        String url = signedUrl.toString();

        log.info("生成的签名URL: {}", url);
        return url;
    }

    /**
     * 删除文件
     *
     * @param objectName 对象名称
     */
    public void deleteFile(String objectName) {
        OSS ossClient = createOssClient();
        try {
            ossClient.deleteObject(bucketName, objectName);
            log.info("删除文件成功: {}", objectName);
        } catch (OSSException oe) {
            log.error("删除文件失败: {}", oe.getMessage());
            throw new RuntimeException("删除文件失败", oe);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}